package com.bangbang.controller;


import com.bangbang.feign.PayServiceFeign;
import com.bangbang.configresult.Result;
import com.bangbang.configresult.ResultEnum;
import com.bangbang.pojo.TbGroupCourse;
import com.bangbang.pojo.TbGroupCourseOrder;
import com.bangbang.service.ITbGroupCourseOrderService;
import com.bangbang.service.ITbGroupCourseService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 拼团课程商品信息表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-08-13
 */
@RestController
@RequestMapping("/groupCourse/tbGroupCourse")
public class TbGroupCourseController {

    @Autowired
    private ITbGroupCourseService groupCourseService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PayServiceFeign payServiceFeign;

    @Autowired
    private ITbGroupCourseOrderService orderService;

/*    @Autowired
    private CreatGroupCourseOrderServiceFeignHalf orderServiceFeignHalf;*/

    @ApiOperation("查询拼团表")
    @GetMapping
    public Result selectGroupCourse(){
        List<TbGroupCourse> TbGroupCourse =  groupCourseService.selectGroupCourse();

        return Result.buildResult(ResultEnum.SUCCESS).setResult(TbGroupCourse);
    }

    //教师端发起拼团
    @ApiOperation("教师发起拼团")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupCourse", value = "拼团发起信息", paramType = "body"),
    })
    @PostMapping("create")
    public Result creatGroupCourse(TbGroupCourse groupCourse){
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        /*IdWorker idWorker = new IdWorker();
        long id = idWorker.nextId();
        groupCourse.setGroId(id);*/
        groupCourseService.creatGroupCourse(groupCourse);
        Map<String,Object> map = new HashMap<>();
        map.put("beginTime",groupCourse.getGroBeginTime());
        map.put("endTime",groupCourse.getGroFinishTime());
        map.put("groPerson",groupCourse.getGroPerson());
        long l =  groupCourse.getGroFinishTime().getTime() - groupCourse.getGroBeginTime().getTime();
        //教师id、拼团id、拼团时间段集合
        redisTemplate.opsForHash().put(groupCourse.getGroTeacherId(),groupCourse.getGroId(),map);
        redisTemplate.opsForValue().set(groupCourse.getGroId(),groupCourse.getGroPerson().toString());
        redisTemplate.expire(groupCourse.getGroId(),l, TimeUnit.SECONDS);
        return Result.buildResult(ResultEnum.SUCCESS);
    }

    //学生看到拼团 加入拼团
    @ApiOperation("学生加入拼团")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户姓名", required = true, paramType = "query"),
            @ApiImplicitParam(name = "groTeacherId", value = "教师ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "groId", value = "拼团ID", required = true,paramType = "query"),
            @ApiImplicitParam(name = "groGroupPrice", value = "课程拼团价", required = true,paramType = "query")
    })
    @PostMapping("join")
    private String joinGroupCourse(@RequestParam("userId")Long userId,@RequestParam("userName") String userName, @RequestParam("groTeacherId")Long groTeacherId, @RequestParam("groId")Long groId, @RequestParam("groGroupPrice")BigDecimal groGroupPrice){
        redisTemplate.setValueSerializer(new StringRedisSerializer());
       // 获取当前登录用户的信息  手机号、姓名等
        //TODO
        String userPhone = "13353733989";

        //查询redis 查看是否符合时间
        Map<String,Object> map = (Map<String, Object>) redisTemplate.opsForHash().get(groTeacherId, groId);
        if(map==null){
            return "暂无该课程";
        }
        Date beginTime = (Date) map.get("beginTime");
        Date endTime = (Date) map.get("endTime");
        Date date = new Date();
        if (map.size()>0 && date.getTime() >= beginTime.getTime() && date.getTime() <= endTime.getTime()){
            Boolean hasKey = redisTemplate.hasKey(groId);
            Boolean hasKey2 = redisTemplate.hasKey(groTeacherId);
            if(hasKey && hasKey2) {
                String person = (String) redisTemplate.opsForValue().get(groId);
                long l = Long.parseLong(person+"");
                if (l <= 0) {
                    //拼团失败，人数已满
                    redisTemplate.delete(groId);
                    redisTemplate.delete(groTeacherId);
                    return "拼团失败，请寻找其他拼团";
                } else {
                    //拼团成功执行生成订单
                    Long decrement = redisTemplate.opsForValue().decrement(groId);
                    if(decrement<0){
                        //删除redis信息
                        redisTemplate.delete(groId);
                        return "拼团人数已满";
                    }
                    TbGroupCourseOrder courseOrder = new TbGroupCourseOrder();
                /*//idwork生产订单号
                IdWorker idWorker = new IdWorker();
                long l = idWorker.nextId();*/
                    courseOrder.setGcoGroPrice(groGroupPrice).setGcoUserId(userId).setGcoTeacherId(groTeacherId).setGcoCreateTime(new Date());
                    courseOrder.setGcoReceiver(userName).setGcoReceiverMobile(userPhone);
                    // TbGroupCourseOrderDTO courseOrderDTO = new TbGroupCourseOrderDTO();
                    // BeanUtils.copyProperties(courseOrder, courseOrderDTO);
                    //生成订单
                    orderService.createOrder(courseOrder);
                    System.err.println(courseOrder.getGcoId());
                    //调用接口 TODO
                    String stringrResult = payServiceFeign.alipayTradePagePay(courseOrder.getGcoId(), groGroupPrice, "拼团购买", "8023");
                    System.err.println(stringrResult);
                    return stringrResult;
                }
            }
        }
        //调用支付接口返回流水号
        return "不在拼团时间";
    }

    //教师删除 未开始的拼团
    @ApiOperation("教师删除未开始拼团")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groTeacherId", value = "教师ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "groId", value = "拼团ID", required = true,paramType = "query"),
    })
    @DeleteMapping("deleteGroup")
    private Result deleteGroup(@RequestParam("groTeacherId")Long groTeacherId, @RequestParam("groId")Long groId){
        //查询redis 查看是否符合时间
        Map<String,Object> map = (Map<String, Object>) redisTemplate.opsForHash().get(groTeacherId, groId);
        if(map==null){
            return Result.buildResult(ResultEnum.ERROR).setResult("暂无该课程");
        }
        Date beginTime = (Date) map.get("beginTime");
        Date endTime = (Date) map.get("endTime");
        Date date = new Date();
        if (map.size()>0 && date.getTime() <= beginTime.getTime() || date.getTime() >= endTime.getTime()){
            Boolean hasKey = redisTemplate.hasKey(groId);
            Boolean hasKey2 = redisTemplate.hasKey(groTeacherId);
            if(hasKey && hasKey2) {
                redisTemplate.delete(groId);
                redisTemplate.delete(groTeacherId);
            }
            groupCourseService.removeById(groId);//删除数据库
            return Result.buildResult(ResultEnum.ERROR).setResult("删除拼团成功");
        }
        return Result.buildResult(ResultEnum.SUCCESS).setResult("删除拼团失败，该活动已在进行");
    }

}

